import { defineFakeRoute } from "vite-plugin-fake-server/client";
import { navData, chartData } from "./analysis-data";

function findField(data, targetName, key = "name") {
  if (Array.isArray(data)) {
    // 如果当前数据是数组
    for (const item of data) {
      if (typeof item === "object" && item !== null) {
        // 确保是对象
        if (item[key] === targetName) {
          return item; // 找到匹配的 name，返回该对象
        }
        const found = findField(item.children, targetName, key); // 递归查找
        if (found) return found; // 如果找到了就直接返回
      }
    }
  }
  return null; // 没有找到返回 null
}

export default defineFakeRoute([
  {
    url: "/datalist",
    method: "post",
    response: ({ body }) => {
      if (body) {
        if (body.name) {
          const item = findField(navData, body.name);
          if (item) {
            return {
              code: 200,
              data: item.children
            };
          }
        }
      }
      return {
        code: 200,
        data: navData
      };
    }
  },
  {
    url: "/datachart",
    method: "post",
    response: () => {
      return {
        code: 200,
        data: chartData
      };
    }
  }
]);
